package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constant.MessageConstant;
import com.example.context.BaseContext;
import com.example.dto.LoginDTO;
import com.example.dto.PageDTO;
import com.example.dto.RegisterDTO;
import com.example.dto.UserDTO;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.query.UserQuery;
import com.example.result.Result;
import com.example.service.IUserService;
import com.example.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    /*
    * 用户登录
    * @param loginDTO
    * @return
    * */
    @Override
    public User login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        //根据用户名查询用户
        User user = getUser(username);
        //判断用户是否存在
        if(user == null){
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!user.getPassword().equals(password)){
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }
        return user;
    }



    /*
    * 用户注册
    * @param registerDTO
    * @return
    * */
    @Override
    public void register(RegisterDTO registerDTO) {
        String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();
        //判断用户名和密码是否都是4到16个字符
        if(username.length() < 4 || username.length() > 16 || password.length() < 4 || password.length() > 16){
            throw new RuntimeException(MessageConstant.PASSWORD_OR_USERNAME_LENGTH_ERROR);
        }
        //判断用户是否存在
        User user = getUser(username);
        if (user != null){
            throw new RuntimeException(MessageConstant.ACCOUNT_ALREADY_EXISTS);
        }
        //判断两次密码是否一致
        String password2 = registerDTO.getPassword2();
        if (!password.equals(password2)){
            throw new RuntimeException(MessageConstant.PASSWORD_INCONSISTENCY);
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //保存用户
        User newuser = User.builder()
                .username(username)
                .password(password)
                .build();
        save(newuser);
    }

    /*
    * 用户信息更新
    * @param userdto
    * @return
    * */
    @Override
    public void updateUser(UserDTO userDTO) {
        if(userDTO.getPassword()!= null && (!userDTO.getPassword().equals(userDTO.getPassword2()))){
            throw new RuntimeException(MessageConstant.PASSWORD_INCONSISTENCY);
        }
        Long id = userDTO.getId();
        //获取用户原始信息
        User user = getById(id);
        String password = userDTO.getPassword();
        if (password != null) {
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            userDTO.setPassword(password);
            if(user.getPassword().equals(password)){
                throw new RuntimeException(MessageConstant.NEW_PASSWORD_SAME_AS_OLD_PASSWORD);
            }
        }
        BeanUtils.copyProperties(userDTO, user);
        //更新用户信息
        updateById(user);
    }

    /*
    * 分页查询用户
    * @param userQuery
    * @return
    * */
    @Override
    public Result<PageDTO<UserVO>> QueryUserpage(UserQuery userQuery) {
        String username = userQuery.getUsername();
        Integer role = userQuery.getRole();
        Integer status = userQuery.getStatus();
        //构造分页对象
        Page<User> page = userQuery.toMpPage();
        //构造查询条件
        Page<User> p = lambdaQuery()
                .like(username != null, User::getUsername, username)
                .eq(role != null, User::getRole, role)
                .eq(status != null, User::getStatus, status)
                .page(page);
        //转换为VO
        PageDTO<UserVO> pageDTO = PageDTO.of(p, UserVO.class);
        return Result.success(pageDTO);
    }

    /*
    * 根据用户名查询用户
    * @param username
    * @return
    * */
    private User getUser(String username) {
        //根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = getOne(queryWrapper);
        return user;
    }
}
